/**
 * Copyright (C) 2010 Cloudfarming <info@cloudfarming.nl>
 *
 * Licensed under the Eclipse Public License - v 1.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *         http://www.eclipse.org/legal/epl-v10.html
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package nl.cloudfarming.client.geoviewer.layers;

import nl.cloudfarming.client.geoviewer.Category;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import nl.cloudfarming.client.geoviewer.Layer;
import nl.cloudfarming.client.geoviewer.LayerObject;
import nl.cloudfarming.client.geoviewer.MapController;
import org.openide.nodes.Children;
import org.openide.nodes.Index;
import org.openide.nodes.Node;
import org.openide.util.Utilities;

/**
 * Used to initialize the nodes for the layers.
 * 
 * @author Timon Veenstra
 */
public class LayerChildren extends Children.SortedArray implements Index {

    private Category category;
    private MapController mapApi;
    /** Permits changing order of children. */
    private Index indexSupport;

    public LayerChildren(MapController mapApi, Category category) {
        this.category = category;
        this.mapApi = mapApi;

        // support for the sorting and rearranging of the elements
        indexSupport = new IndexSupport();
    }

    /**
     * Initializes the layers (Nodes)
     */
    @Override
    @SuppressWarnings("unchecked")
    protected void addNotify() {
        super.addNotify();

        nodes = new ArrayList<Node>();
        Set<Layer<LayerObject<?>>> layers = mapApi.getLayers();
        //TODO inverse collection for right order
        //Collections.reverse(layerIds);
        for (Layer layer : layers) {
            if (category.equals(layer.getCategory())) {
                Node node = new LayerNode(mapApi, layer);
                nodes.add(node);
            }

        }


        

    }

    /**
     * Adds a changelistener
     * @param l
     */
    public void addChangeListener(ChangeListener l) {
        indexSupport.addChangeListener(l);
    }

    /**
     * Removes a changelistener
     * @param l
     */
    public void removeChangeListener(ChangeListener l) {
        indexSupport.removeChangeListener(l);
    }

    /**
     * Exchanges the position of two child indexes
     * @param x
     * @param y
     */
    public void exchange(int x, int y) {
        indexSupport.exchange(x, y);
    }

    /**
     * Returns the index of the node
     * @param node
     * @return
     */
    public int indexOf(Node node) {
        return indexSupport.indexOf(node);
    }

    /**
     * Moves the index up
     * @param i
     */
    public void moveUp(int i) {
        indexSupport.moveUp(i);
    }

    /**
     * Moves the index down
     * @param i
     */
    public void moveDown(int i) {
        indexSupport.moveDown(i);
    }

    /**
     * Moves a child from position x to position y
     * @param x
     * @param y
     */
    public void move(int x, int y) {
        indexSupport.move(x, y);
    }

    /**
     * Initiates a reorder of the children
     */
    public void reorder() {
        indexSupport.reorder();
    }

    /**
     * Initiates a reorder of the children, by the specified permutation (order)
     * @param order
     */
    public void reorder(int[] order) {
        indexSupport.reorder(order);
    }

    /**
     * Allows re-ordering of the child nodes. Only for private use.
     */
    private class IndexSupport extends Index.Support {

        /**
         * Reorders the nodes, according to the specified ordering (permutations)
         * @param perm
         */
        public void reorder(int[] perm) {

            // get the nodes that need to be reordered
            Node[] nodeArray = nodes.toArray(new Node[]{});
            List<Node> nodesList = new ArrayList<Node>(nodes);
            for (int i = 0; i < nodeArray.length; i++) {
                nodesList.set(perm[i], nodeArray[i]);
            }

            nodes = nodesList;

            // called to initiate a sort
            LayerChildren.this.setComparator(null);

            // make sure the layers on the map are reordered too (reverse ordering, since the layerlist and pane are ordered in the opposite way)
            MapController mapApi = Utilities.actionsGlobalContext().lookup(MapController.class);
            assert (mapApi != null) : "mapApi is null";

            mapApi.setLayerOrder(reverseOrder(perm), LayerChildren.this.category);

            // notify any eventlisteners
            fireChangeEvent(new ChangeEvent(LayerChildren.this));
        }

        /**
         * Returns the number of nodes in the encapsulating object
         * @return int the number of nodes
         */
        @Override
        public int getNodesCount() {
            return LayerChildren.this.getNodesCount();
        }

        /**
         * Returns an array containing the nodes of this child.
         * @return Node[] The childnodes
         */
        @Override
        public Node[] getNodes() {
            return LayerChildren.this.getNodes();
        }

        /**
         * Returns the array, in reverse order
         * Maybe move to some util class?
         * @param order The array that should be reversed
         * @return The reversed array
         */
        private int[] reverseOrder(int[] order) {

            int[] reverseOrder = new int[order.length];
            for (int i = 0; i < order.length; i++) {
                reverseOrder[i] = Math.abs(order.length - 1 - order[order.length - 1 - i]);

            }

            return reverseOrder;
        }
    }
}
